package 多线程.消费者生产者;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ProducerAndConsumer2 {
    public static void main(String[] args) {
        PAC pac = new PAC();
        new Thread(()->{
            pac.produce();
        },"生产者1").start();
        new Thread(()->{
            pac.consume();
        },"消费者1").start();
    }

}

class PAC{
    private final int MAX_VALUE = 20;
    private final Queue<String> produceAndConsumeQueue = new LinkedList<>();
    private final Lock lock = new ReentrantLock();
    private final Condition con = lock.newCondition();

    public void produce(){
        while(true){
            lock.lock();
            try{

                while(produceAndConsumeQueue.size()==MAX_VALUE){
                    System.out.println("队列已满，无法放置物品");
                    con.await();
                }
                produceAndConsumeQueue.add("物品" + produceAndConsumeQueue.size());
                con.signal();
                System.out.println(Thread.currentThread().getName()+"生产了一件物品，当前队列有"+produceAndConsumeQueue.size()+"件物品");

                Thread.sleep(500);

            }catch(Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }

    }

    public void consume(){
        while(true){
            lock.lock();
            try{

                while(produceAndConsumeQueue.size()==0){
                    System.out.println("队列为空，没有物品");
                    con.await();
                }
                String remove = produceAndConsumeQueue.remove();
                con.signal();
                System.out.println(Thread.currentThread().getName()+"消费"+remove+"当前队列有"+produceAndConsumeQueue.size()+"件物品");

                Thread.sleep(500);

            }catch(Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }

    }
}
